package cn.suzhang.jsharp.module.sys.service;

import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.suzhang.jsharp.common.dao.BaseDao;
import cn.suzhang.jsharp.common.service.BaseService;
import cn.suzhang.jsharp.module.sys.dao.RoleDao;
import cn.suzhang.jsharp.module.sys.entity.SysResource;
import cn.suzhang.jsharp.module.sys.entity.SysRole;

@Service
public class RoleService extends BaseService<SysRole, Long> {

    @Autowired
    private RoleDao roleDao;

    @Autowired
    private ResourceService resourceService;

    @Override
    public BaseDao<SysRole, Long> getBaseDao() {
        return roleDao;
    }

    public void saveOrUpdate(SysRole role) {
        if (role.getId() != null) {
            SysRole dbRole = find(role.getId());
            dbRole.setRoleName(role.getRoleName());
            dbRole.setStatus(role.getStatus());
            update(dbRole);
        } else {
            save(role);
        }
    }

    public void grant(Long id, String[] resourceIds) {
        SysRole role = find(id);

        SysResource resource;
        Set<SysResource> resources = new HashSet<SysResource>();
        if (resourceIds != null) {
            for (int i = 0; i < resourceIds.length; i++) {
                if (StringUtils.isBlank(resourceIds[i]) || "0".equals(resourceIds[i])) {
                    continue;
                }
                Long rid = Long.parseLong(resourceIds[i]);
                resource = resourceService.find(rid);
                resources.add(resource);
            }
        }
        role.setResources(resources);
        update(role);
    }

}
